// src/app/workspace/[workspaceId]/_components/workspace-switcher.tsx
import React, {useEffect, useState} from 'react';
import {DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger} from "@/components/ui/dropdown-menu";
import {Button} from "@/components/ui/button";
import {useWorkspaceId} from "@/hooks/social/use-workspace-id";
import {useGetWorkspace} from "@/features/workspaces/api/use-get-workspace";
import {useGetWorkspaces} from "@/features/workspaces/api/use-get-workspaces";
import {Workspace} from "@/lib/social/types";
import {useCreateWorkspaceModal} from "@/features/workspaces/store/use-create-workspace-modal";
import {Loader, Plus} from "lucide-react";
import {useRouter} from "next/navigation";
import {useGetMembers} from "@/features/workspaces/api/use-get-members";
import {useCurrentUser} from "@/hooks/use-current-user";

const WorkspaceSwitcher = () => {
    const user = useCurrentUser()

    const router = useRouter()

    const workspaceId = useWorkspaceId()
    const [workspace, setWorkspace]
        = useState<Workspace | null>();
    // const [workspaces, setWorkspaces]
    //     = useState<Workspace[] | null>();
    const [filteredWorkspaces, setFilteredWorkspaces]
        = useState<Workspace[] | null>();

    const [_open, setOpen] = useCreateWorkspaceModal()

    useEffect(() => {
        (async () => {
            // 获取该用户工作区
            const {data: members} =
                await useGetMembers({
                    wid: workspaceId as string,
                    uid: user?.id!
                })
            if (!members || members.length === 0) {
                setOpen(true)
                return
            }

            // 获取当前工作区
            if (!workspaceId) return
            const {data, isLoading} =
                await useGetWorkspace({id: workspaceId as string})
            if (isLoading) return
            setWorkspace(data)

            // 获取(该用户)其他工作区
            const w = await useGetWorkspaces({uid: user?.id})
            // setWorkspaces(w)
            setFilteredWorkspaces(w?.filter(
                (work: Workspace) => work?.id !== workspaceId
            ))
        })()
    }, [workspaceId]);


    return (
        <DropdownMenu>
            {/*asChild: 防止button can't have button children?*/}
            <DropdownMenuTrigger asChild>
                <Button className={`size-9 min-h-9 min-w-9 relative overflow-hidden bg-[#ababad] hover:bg-[#ababad]/80
                text-slate-800 font-semibold text-xl`}>
                    {!workspace ? (
                        <Loader className={`size-5 animate-spin shrink-0`}/>
                    ) : (
                        workspace?.name.charAt(0).toUpperCase()
                    )}
                </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent side={'bottom'} align={'start'} className={`w-64`}>
                <DropdownMenuItem
                    onClick={() => router.push(`/social/workspace/${workspaceId}`)}
                    className={`cursor-pointer flex-col justify-start items-start capitalize`}
                >
                    {workspace?.name}
                    {/*重定向到工作区的主页*/}
                    <span className={`text-xs text-muted-foreground`}>
                        Active workspace
                    </span>
                </DropdownMenuItem>
                {filteredWorkspaces?.map((w: Workspace) => (
                    <DropdownMenuItem
                        key={w.id}
                        className={`cursor-pointer capitalize`}
                        onClick={() => router.push(`/social/workspace/${w.id}`)}
                    >
                        <div className={`size-9 min-h-9 min-w-9 relative overflow-hidden bg-[#616061] text-white
            font-semibold text-lg rounded-md flex items-center justify-center mr-2`}>
                            {w?.name.charAt(0).toUpperCase()}
                        </div>
                        <p className={`truncate`}>{w.name}</p>
                    </DropdownMenuItem>
                ))}
                <DropdownMenuItem
                    className={`cursor-pointer`}
                    onClick={() => setOpen(true)}
                >
                    <div className={`size-9 relative overflow-hidden bg-[#f2f2f2] text-slate-800
            font-semibold text-lg rounded-md flex items-center justify-center mr-2`}>
                        <Plus className={``}/>
                    </div>
                    Create a new workspace
                </DropdownMenuItem>
            </DropdownMenuContent>
        </DropdownMenu>
    );
};

export default WorkspaceSwitcher;